package com.novel.system.controller;

import com.novel.common.constants.UserConstants;
import com.novel.common.exception.business.BusinessException;
import com.novel.framework.annotation.Log;
import com.novel.framework.base.BaseController;
import com.novel.framework.enums.BusinessType;
import com.novel.framework.result.Result;
import com.novel.framework.shiro.utils.ShiroUtils;
import com.novel.framework.validate.groups.AddGroup;
import com.novel.framework.validate.groups.EditGroup;
import com.novel.framework.web.page.TableDataInfo;
import com.novel.system.domain.SysDept;
import com.novel.system.domain.SysRole;
import com.novel.system.service.SysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 部门信息
 *
 * @author novel
 * @date 2019/5/15
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    private final SysDeptService deptService;

    public SysDeptController(SysDeptService deptService) {
        this.deptService = deptService;
    }

    /**
     * 部门列表
     *
     * @param dept 部门列表查询条件
     * @return 部门列表信息
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/list")
    public TableDataInfo list(SysDept dept) {
        startPage();
        return getDataTable(deptService.selectDeptList(dept));
    }

    /**
     * 树形部门列表信息
     *
     * @param dept 部门列表查询条件
     * @return 部门列表信息
     */
    @RequiresPermissions("system:dept:list")
    @GetMapping("/deptTreeTableData")
    public Result deptTreeTableData(SysDept dept) {
        return toAjax(deptService.deptTreeTableData(dept));
    }

    /**
     * 新增保存部门
     *
     * @param dept 部门信息
     * @return 新增结果
     */
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:dept:add")
    @PostMapping("/add")
    public Result addSave(@Validated(AddGroup.class) SysDept dept) {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            throw new BusinessException("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(ShiroUtils.getUserName());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 编辑部门信息
     *
     * @param dept 部门信息
     * @return 修改结果
     */
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:dept:edit")
    @PutMapping("/edit")
    public Result editSave(@Validated(EditGroup.class) SysDept dept) {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            throw new BusinessException("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId() != null && dept.getParentId().equals(dept.getId())) {
            throw new BusinessException("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        dept.setUpdateBy(ShiroUtils.getUserName());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     *
     * @param ids 部门id
     * @return 操作结果
     */
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:menu:remove")
    @DeleteMapping("/remove")
    public Result remove(Long[] ids) {
        return toAjax(deptService.deleteMenuByIds(ids));
    }


    /**
     * 校验部门名称
     *
     * @param dept 包含部门名称的部门对象
     * @return 结果
     */
    @PostMapping("/checkDeptNameUnique")
    public Result checkDeptNameUnique(SysDept dept) {
        return toAjax(deptService.checkDeptNameUnique(dept));
    }

    /**
     * 加载部门列表树
     *
     * @return 部门列表树
     */
    @GetMapping("/deptTreeSelectData")
    public Result treeData() {
        return toAjax(deptService.deptTreeSelectData());
    }

    /**
     * 加载角色部门（数据权限）列表树
     *
     * @param role 角色信息
     * @return 色部门（数据权限）列表树
     */
    @GetMapping("/roleDeptTreeData")
    public List<Map<String, Object>> deptTreeData(SysRole role) {
        return deptService.roleDeptTreeData(role);
    }

    /**
     * 根据id查询部门
     *
     * @param id 部门id
     * @return 部门信息
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") @NotNull(message = "部门ID不能为空") @Min(value = 1, message = "部门ID必须大于0") Long id) {
        return toAjax(deptService.selectDeptById(id));
    }
}
